package com.xindaoapp.happypet.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.View;

import com.xindaoapp.happypet.utils.CommonUtil;


public class MxxBlurView extends View {

    int radius = 30;
    private Canvas mCanvas;
    private Bitmap mBitmap;
    private Rect mRectVisibleGlobal;
    private Matrix mMatrixScale;
    private Matrix mMatrixScaleInv;
    float BITMAP_SCALE_FACTOR = 0.2f;

    public MxxBlurView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
        init();
    }

    public MxxBlurView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        init();
    }

    public MxxBlurView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        init();
    }

    // 进行一次高斯模糊
    public void drawBlurOnce() {
        drawOffscreenBitmap(this);
        this.setBackgroundDrawable(new BitmapDrawable(FastBlur.doBlur(mBitmap, radius, true)));
    }

    private void init() {
        mMatrixScale = new Matrix();
        mMatrixScaleInv = new Matrix();
        mCanvas = new Canvas();
        mRectVisibleGlobal = new Rect();
        radius = CommonUtil.dip2px(getContext(), radius);
        radius = Math.round(radius * BITMAP_SCALE_FACTOR);
    }

    // 把该View后面的一层绘制为bitmap
    public Bitmap drawOffscreenBitmap(View mView) {

        mView.getGlobalVisibleRect(mRectVisibleGlobal);


        int width = Math.round(mView.getWidth() * BITMAP_SCALE_FACTOR);
        int height = Math.round(mView.getHeight() * BITMAP_SCALE_FACTOR);

        // This is added due to RenderScript limitations I faced.
        // If bitmap width is not multiple of 4 - in RenderScript
        // index = y * width
        // does not calculate correct index for line start index.
        width = width & ~0x03;
        width = Math.max(width, 1);
        height = Math.max(height, 1);

        if (mBitmap == null || mBitmap.getWidth() != width || mBitmap.getHeight() != height) {
            mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            mMatrixScale.setScale((float) width / mView.getWidth(),
                    (float) height / mView.getHeight());
            mMatrixScale.invert(mMatrixScaleInv);
        }
        int dx = -(Math.min(0, mView.getLeft()) + mRectVisibleGlobal.left);
        int dy = -(Math.min(0, mView.getTop()) + mRectVisibleGlobal.top);
        mCanvas.restoreToCount(1);
        mCanvas.setBitmap(mBitmap);

        mCanvas.setMatrix(mMatrixScale);
        mCanvas.translate(dx, dy);
        mCanvas.save();
        mView.getRootView().draw(mCanvas);
        return mBitmap;
    }

}
